
layui.use(['form', 'layer', 'table', 'formSelects'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;
    var formSelects = layui.formSelects;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var handle_url = $('.handle_url').val();


    if($('#coupons').length > 0){
        formSelects.render('coupons');
    }

    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            {field: 'name', title: '等级名称', align:'center'},
            {field: 'first_single_reduction', title: '首单立减', align:'center'},
            {field: 'integral_quantity', title: '消费送积分', align:'center'},
            {field: 'recharge_rule_id', title: '充值送现金', align:'center'},
            {field: 'birthday_quantity', title: '生日送积分', align:'left'},
            {field: 'countCoupons', title: '超级券', align:'center'},
            {field: 'payment_rules', title: '开通费用', align:'center', minWidth:200},
            {field: 'create_date', title: '添加时间', align:'center', minWidth:110, sort: true},
            {field: 'status', title: '状态', align:"center", templet:function(data){
                var html = '';
                if (data.id == 1) {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'" checked disabled>';
                } else {
                    if (data.status == 1) {
                        html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'" checked>';
                    } else {
                        html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'">';
                    }
                }

                return html;
            }},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                if(data.id != 1){
                    html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                }

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){
        if($('.name').val() != ''){
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    name: $('.searchBox').find('input[name=name]').val()  // 搜索的关键字
                }
            });
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function(){
        table.reload("tableList", {
            where: {
                name: ''
            }
        });
    });

    // Status 操作
    form.on('switch(status)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});

        var status = 2;
        if(data.elem.checked){
            status = 1;
        }

        $.ajax({
            url: handle_url,
            data: {'id' : data.elem.value,'status' : status},
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){
            formHtml(data);
        }
    });

    // 删除
    /*$('.del-btn').on('click', function(){
        layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
            $.ajax({
                url: delete_url,
                data: {"id": data.id},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('已删除', {icon: 1, time: 1000});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        });
    });*/

    // Form 表单
    function formHtml(data){
        var content = add_url;
        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: -1
            , title: false
            , closeBtn: false
            , offset: 'r'
            , shade: 0.1
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: '800px'
            , top: 0
            , content: content
        });
    }

    // 是否付费开通会员
    form.on('switch(is_payment)', function(data){
        if (data.elem.checked) {
            $('.payment-rule').show();
        } else {
            $('.payment-rule').hide();
        }
    });

    // 添加费用标准
    $('.addRule-btn').on('click', function(){
        var rule_length = $('.payment-rule-group').find('.rule-group').length;
        var $html = '';
        $html += '<div class="layui-form-item layui-form-text rule-group">';
            $html += '<div class="layui-inline">';
                $html += '<label class="layui-form-label"><span class="required">*</span>费用</label>';
                $html += '<div class="layui-input-inline">';
                $html += '<input type="text" class="layui-input vip_cost" name="vip_cost['+rule_length+']" maxlength="10" placeholder="元" autocomplete="off">';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<label class="layui-form-label" style="width: 40px;"><span class="required">*</span>时长</label>';
                $html += '<div class="layui-input-inline">';
                $html += '<input type="text" class="layui-input vip_time" name="vip_time['+rule_length+']" maxlength="10" placeholder="月" autocomplete="off">';
                $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
                $html += '<div class="layui-input-inline">';
                $html += '<button type="button" class="layui-btn layui-btn-danger delRule-btn"><i class="layui-icon layui-icon-delete"></i></button>';
                $html += '</div>';
            $html += '</div>';
        $html += '</div>';

        $('.payment-rule-group').append($html);
    });

    // 删除费用标准
    $('.payment-rule-group').on('click', '.delRule-btn', function(){
        $(this).parents('.rule-group').remove();
    });

    // 自定义验证规则
    form.verify({
        name: function(value){
            if(value == ''){
                return '等级名称不能为空';
            }
            if(value.length > 20){
                return '等级名称最多为20个字符';
            }
        },
        first_single_reduction: function(value){
            if(!$('input[name=is_first_order]').next().hasClass('layui-form-onswitch')){
                return;
            }
            if(value == ''){
                return '立减金额占首单金额比例不能为空';
            }
            if(!/^[1-9][0-9]{0,1}$/.test(value)){
                return '立减金额占首单金额比例格式不正确，应在1-99之间';
            }
        },
        integral_quantity: function(value){
            if(!$('input[name=is_gives_points]').next().hasClass('layui-form-onswitch')){
                return;
            }
            if(value == ''){
                return '每消费1元送积分不能为空';
            }
            if(!/^\+?[1-9][0-9]*$/.test(value)){
                return '每消费1元送积分格式不正确，应为大于0的正整数';
            }
        },
        recharge_rule_id: function(value){
            if(!$('input[name=is_recharge]').next().hasClass('layui-form-onswitch')){
                return;
            }
            if(value == ''){
                return '请选择充值模板';
            }
        },
        birthday_quantity: function(value){
            if(!$('input[name=is_birthday_integral]').next().hasClass('layui-form-onswitch')){
                return;
            }
            if(value == ''){
                return '会员生日免费送积分不能为空';
            }
            if(!/^\+?[1-9][0-9]*$/.test(value)){
                return '会员生日免费送积分格式不正确，应为大于0的正整数';
            }
        },
        coupon_ids: function(value){
            if(!$('input[name=is_coupon]').next().hasClass('layui-form-onswitch')){
                return;
            }
            if(value == ''){
                return '请选择超级券';
            }
        },
    });

    // 检查费用标准
    var checkPaymentRule = function() {
        var status = 1,
            elm = '',
            msg = '';
        $('.payment-rule-group').find('.rule-group').each(function (i) {
            var vip_cost_elm = $(this).find('.vip_cost');
            var vip_time_elm = $(this).find('.vip_time');
            var vip_cost = vip_cost_elm.val();
            var vip_time = vip_time_elm.val();
            if(vip_cost.trim() == ''){
                status = 0;
                elm = vip_cost_elm;
                msg = '费用不能为空';
                return false; // 跳出循环
            }
            if(!/^(([1-9]\d*)|\d)(\.\d{1,2})?$/.test(vip_cost)){
                status = 0;
                elm = vip_cost_elm;
                msg = '费用格式不正确，应为正整数，或者小数点后只有两位的小数';
                return false;
            }
            if(vip_cost <= 0){
                status = 0;
                elm = vip_cost_elm;
                msg = '费用应大于0';
                return false;
            }

            if(vip_time.trim() == ''){
                status = 0;
                elm = vip_time_elm;
                msg = '时长不能为空';
                return false;
            }
            if(!/^\+?[1-9][0-9]*$/.test(vip_time)){
                elm = vip_time_elm;
                msg = '时长格式不正确，应为大于0的正整数';
                return false;
            }
        });

        return {'status':status, 'elm':elm, 'msg':msg};
    };

    // 表单提交
    form.on("submit(laySave)", function(data){
        if(data.field.is_payment == 'on'){
            // 检查费用标准
            var paymentRule = checkPaymentRule();
            //console.log(paymentRule);
            if(paymentRule.status != 1){
                paymentRule.elm.focus();
                layer.msg(paymentRule.msg, {icon: 5});
                return;
            }
        }

        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        if(data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }
        // 是否开启首单立减
        if(data.field.is_first_order == 'on') {
            data.field.is_first_order = 1;
        } else {
            data.field.is_first_order = 2;
            data.field.first_single_reduction = '';
        }
        // 是否开启消费送积分
        if(data.field.is_gives_points == 'on') {
            data.field.is_gives_points = 1;
        } else {
            data.field.is_gives_points = 2;
            data.field.integral_quantity = '';
        }
        // 是否充值送现金
        if(data.field.is_recharge == 'on') {
            data.field.is_recharge = 1;
        } else {
            data.field.is_recharge = 2;
            data.field.recharge_rule_id = '';
        }
        // 是否开启生日送积分
        if(data.field.is_birthday_integral == 'on') {
            data.field.is_birthday_integral = 1;
        } else {
            data.field.is_birthday_integral = 2;
            data.field.birthday_quantity = '';
        }
        // 是否开启赠送送优惠券
        if(data.field.is_coupon == 'on') {
            data.field.is_coupon = 1;
        } else {
            data.field.is_coupon = 2;
            data.field.coupon_ids = '';
        }
        // 是否付费开通会员
        if(data.field.is_payment == 'on') {
            data.field.is_payment = 1;
        } else {
            data.field.is_payment = 2;
            data.field.payment_rules = '';
        }

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if(res.code == 1){
                    layer.closeAll("iframe");
                    parent.layui.table.reload('tableList', {});
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    })

});